package com.note.user.controller;

import com.note.user.constants.ResponseCodeConstants;
import com.note.user.dto.UserDto;
import com.note.user.dto.UserLoginResponseDto;
import com.note.user.enums.ResponseEnum;
import com.note.user.service.TokenService;
import com.note.user.service.UserLoginService;
import com.note.user.util.DigestUtil;
import com.note.user.vo.ResponseVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Package：com.note.user.controller
 * @Name：UserLoginController
 * @Author：热伊木
 * @Email：uyevan@163.com
 * @Date：2023-12-11-11:05
 * @Description：用户登录控制类
 */
@Slf4j
@RestController
@RequestMapping("/user")
@Tag(name = "UserLoginController", description = "用户登录类相关接口")
public class UserLoginController {

    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private TokenService tokenService;


    @ResponseBody
    @PostMapping("/login")
    @Operation(summary = "login", description = "用户登录接口 (用户名username|密码password)")
    public ResponseVo userLogin(@RequestBody @Validated({UserLoginService.class}) UserDto userDto /*BindingResult bindingResult*/) {
        //参数校验
        /* 接口上判断（已更改到异常判断）
        if (bindingResult.hasErrors()) {
            return new ResponseVo(ResponseCodeConstants.BAD_REQUEST, false, Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
        }
        */
        /*MD5加密数据*/
        userDto.setPassword(DigestUtil.encryptMd5hex(userDto.getPassword()));
        //用户状态验证
        int validateUserCode = userLoginService.validateUser(userDto);
        //令牌初始化
        return switch (validateUserCode) {
            case ResponseCodeConstants.USER_NOT_FOUND -> new ResponseVo(ResponseEnum.USER_NOT_FOUND);
            case ResponseCodeConstants.WRONG_PASSWORD -> new ResponseVo(ResponseEnum.WRONG_PASSWORD);
            case ResponseCodeConstants.USER_BANNED -> new ResponseVo(ResponseEnum.USER_BANNED);
            case ResponseCodeConstants.LOGIN_SUCCESS -> {
                UserLoginResponseDto userLoginResponseDto = new UserLoginResponseDto(tokenService.getToken(userDto));
                yield new ResponseVo(ResponseEnum.LOGIN_SUCCESS, userLoginResponseDto);
            }
            default -> new ResponseVo(ResponseEnum.FAIL);
        };
    }
}
